import {reqlogOut, reqLogin, reqRegister, reqUpdateUser, reqUserInfo} from "@/api";
import {getToken, removeToken, setToken} from "@/utils/token";
const state = {

    code:{},
    token: getToken(),
    userInfo:{}

};
const actions = {
    // 注册
    async ReqRegister({commit},userFrom) {
        //向服务器发送请求，请求注册
        let resultReqRegister = await reqRegister(userFrom);
        console.log(resultReqRegister)
    },

    // 更改个人信息
    async UpdateUser({commit},userFrom) {
        //向服务器发送请求，请求注册
        let resultUpdateUser = await reqUpdateUser(userFrom);
        console.log(resultUpdateUser)
    },

    async ReqLogin({commit},userFrom) {
        let resultReqLogin = await reqLogin(userFrom);
        if (resultReqLogin.access_token){
           setToken(resultReqLogin.access_token)
            commit("LoginInfo",resultReqLogin)
        }
    },
    async ReqUserInfo({commit}){
        let resultReqUserInfo = await reqUserInfo()
        if (resultReqUserInfo.id) {
            console.log(resultReqUserInfo)
            commit("UserInfo",resultReqUserInfo)
            console.log('请求到的用户数据')
            console.log(resultReqUserInfo)
            return 'ok';
        } else {
            return Promise.reject();
        }
    },
    async Logout({dispatch, commit, state}) {
        console.log('退出登录被调用关闭了')
        if (state.userInfo.id){await reqlogOut(state.userInfo.id)}
        removeToken();
        dispatch('DownWebSocket')
        commit("CLEAR")
    }
};
const mutations = {
    LoginInfo(state,resultReqLogin){
        state.token = resultReqLogin.access_token
    },
    UserInfo(state,resultReqUserInfo){
        state.userInfo = resultReqUserInfo
    },
    CLEAR(state){
        state.token = '';
        state.userInfo = '';
    }
};
const getters = {};
export default {
    state,
    mutations,
    actions,
    getters
}
